<template>
	<view>
		<web-view v-if="isLoad" :src="pagePath" @message="getMessage" allow="fullscreen"> </web-view>
	</view>
</template>

<script>
	import wfc from '@/wfc/client/wfc'
	import Config from '@/config'
	import { getItem, setItem, removeItem } from '../util/storageHelper'
	import appServerApi from '@/api/appServerApi'
	import { checkUpdate } from '@/components/yzhua006-update/js/app-update-check.js'
	// import { checkOpenGPSServiceByAndroid } from '@/utils/device.js'
	// import organizationServerApi from '@/api/organizationServerApi'
	import permision from '@/js_sdk/wa-permission/permission.js'

	export default {
		components: {},
		data() {
			return {
				pagePath: '',
				isLoad: false,
				CustomBar: this.CustomBar,
				StatusBar: this.StatusBar
			}
		},
		onReady() {
			var currentWebview = this.$scope.$getAppWebview().children()[0]
			if (currentWebview) {
				currentWebview.addEventListener('loaded', function () {
					currentWebview.evalJS('$("ul.fed-part-rows a[href*=\'resource.i847.cn\']").parent().hide();')
				})
			}
		},
		onBackPress(e) {
			this.$scope.$getAppWebview().children()[0].back()
			return true
		},
		onLoad() {
			// this.createRTC()
		},

		onShow() {
			console.log('login onShow')
			if (
				(Config.APP_SERVER.indexOf('wildfirechat') >= 0 && Config.IM_SERVER_HOST.indexOf('wildfirechat') === -1) ||
				(Config.APP_SERVER.indexOf('wildfirechat') === -1 && Config.IM_SERVER_HOST.indexOf('wildfirechat') >= 0)
			) {
				console.error(
					'!!!! 严重错误!!!! Config.APP_SERVER 和 Config.IM_SERVER_HOST要一起修改，不能一个用官方服务，一个用自己部署的服务'
				)
			} else if (Config.IM_SERVER_HOST.indexOf(':') >= 0) {
				console.error('!!!! 严重错误!!!! Config.IM_SERVER_HOST 不能包含端口，只需要 HOST 即可')
			} else if (Config.IM_SERVER_HOST.indexOf('http') >= 0) {
				console.error('!!!! 严重错误!!!! Config.IM_SERVER_HOST 不能包含http，只需要 HOST 即可')
			}
			// this.getPos()
		},
		mounted() {
			this.initPage()
		},
		// onReady() {
		// 	var pages = getCurrentPages()
		// 	var page = pages[pages.length - 1]
		// 	var currentWebview = page.$getAppWebview()
		// 	var url = currentWebview.children()[0].getURL()
		// 	console.log('=== url ===', url)
		// 	var wv = currentWebview.children()[0]
		// 	wv.overrideUrlLoading(
		// 		{
		// 			mode: 'reject',
		// 			match: '.*'
		// 		},
		// 		function (e) {
		// 			console.log('reject url: ' + e.url)
		// 			uni.navigateTo({
		// 				url: `/pages/webbox/webbox?weburl=${e.url}`
		// 			})
		// 		}
		// 	)
		// },
		// onBackPress(e) {
		// 	let pages = getCurrentPages()
		// 	let page = pages[pages.length - 1]
		// 	let currentPages = page.$getAppWebview()
		// 	currentPages.close()
		// 	return false
		// },

		methods: {
			initPage() {
				plus.push.getClientInfoAsync((info) => {
					let cid = info['clientid']
					this.isLoad = false
					let pagePath = 'pages/index/tabbar'
					const baseUrl = `CustomBar=${this.CustomBar}&StatusBar=${this.StatusBar}&cid=${cid}&t=${new Date().getTime()}`
					// 如果有带参数了，就接上
					pagePath += `?` + baseUrl
					const url = 'http://175.44.138.53:5566' + '/#/' + pagePath
					console.info(`url:`, url)
					this.pagePath = url
					this.isLoad = true
					this.noeMessage()
				})
			},
			hasParams(url) {
				const regex = /[?&]([^=#]+)=([^&#]*)/g
				return regex.test(url)
			},
			getMessage(e) {
				let data = e.detail.data[0]

				if (data.message == 'getLocation') {
					this.getPos()
					return
				}

				if (data.message == 'loginOut') {
					removeItem('token')
					removeItem('userId')
					wfc.disconnect()
					uni.clearStorageSync()
					this.initPage()
					// let page = getCurrentPages()
					// page.clear()
					// uni.reLaunch({ url: '/pages/appPage/index' })
					return
				}

				if (data.message == 'update_version') {
					this.getAppInfo(0, data.data)
					return
				}
				// wfc.init()
				// uni.clearStorageSync()
				// wfc.eventEmitter.on(EventType.ConnectionStatusChanged, this.onConnectionStatusChange)
				const { userInfo, getUserInfoData } = e.detail.data[0]
				uni.setStorageSync('userInfoH5', userInfo)
				uni.setStorageSync('getUserInfoDataH5', getUserInfoData)
				// wfc.disconnect()
				// removeItem('token')
				let userId = userInfo.user_id
				this.connectMessage(userId, '66666') // 'sanyuanqu', '三元区用户'
				// appServerApi.requestAuthCode('17759501371').then((result) => {
				// console.info(`result:`, result)
				// this.connectMessage('17759501371', '908064')
				// })
			},
			login(phone, code) {
				//name, displayName
				uni.showLoading({
					title: '正在通讯'
				})
				appServerApi
					.loginWithAuthCode(phone, code) // name, displayName
					.then((result) => {
						let userId = result.userId
						let token = result.token
						wfc.connect(userId, token)
						setItem('userId', userId)
						setItem('token', token)
						console.info(`1222222:`)
						uni.hideLoading()
						this.connectMessage()
						// this.go2ConversationList();
					})
					.catch((r) => {
						uni.hideLoading()
						uni.showToast({
							title: '通讯失败',
							icon: 'error'
						})
					})
			},
			connectMessage(phone, code) {
				let userId = getItem('userId')
				let token = getItem('token')
				if (token) {
					console.info(`33333333333333:`)
					wfc.connect(userId, token)
					// uni.showToast({
					// 	title: '加载完成',
					// 	icon: 'none'
					// })
					uni.navigateTo({ url: '/pages/conversationList/ConversationListPage' })

					// this.go2ConversationList()
				} else {
					this.login(phone, code)
					//
				}
			},
			recordShow(e) {
				// let start = uni.getRecorderManager()
				// // plus.runtime.openURL('app-settings://')
				// start.start()
				// start.pause()
			},

			// 启动版本更新
			getAppInfo(type, versionJson) {
				const system_info = uni.getSystemInfoSync()
				let params = {
					os: system_info.platform //本机设备操作系统  （android || ios）
				}
				if (params.os != 'ios' && params.os != 'android') false //如果不是安卓或ios 返回false

				//这里自行请求API获取版本信息 建议传入操作系统标识，返回本机对应的操作系统最新版本信息，也就是安卓的返回就是安卓的版本信息  ios返回就是ios的版本信息
				//请求获取最新版本
				setTimeout(() => {
					let update_info = {
						// version: '1.0.6', //线上版本
						// now_url: 'http://test.geoai.com.cn:8923/package/知汛情v1.0.5.apk', //更新链接
						silent: 0, //是否是静默更新
						force: 0, //是否是强制更新
						net_check: 1, //非WIfi是否提示
						note: '升级应用', //更新内容
						...versionJson
					}
					checkUpdate(update_info, type).then((res) => {
						if (res.msg) {
							// plus.nativeUI.toast(res.msg)
						}
					}) ///检查更新
					//checkUpdate 这个方法会做什么？：线上版本号 与 本地版本号做对比 ，如果需要更新  根据静默，强制、wifi等信息执行静默更新或跳转到升级页面
					//跳转升级页面的前提是，需要新建并在pages.json中配置升级页面，配置方法请查看插件详情
				}, 200)
			},
			getPos() {
				uni.getLocation({
					type: 'wgs84',
					// geocode: true, //设置该参数为true可直接获取经纬度及城市信息
					// evalJS 写入参数
					success: (res) => {
						var currentWebview = this.$scope.$getAppWebview().children()[0]
						if (currentWebview) {
							currentWebview.evalJS(`receiveData('${res.latitude},${res.longitude}')`)
						}
					},
					fail: function (ress) {
						//失败 调用
						// checkOpenGPSServiceByAndroid()
					}
				})
			},
			noeMessage() {
				const notificationAuthorized = uni.getAppAuthorizeSetting().notificationAuthorized
				if (notificationAuthorized === 'authorized') {
				} else {
					// console.info(`444:`)
					// uni.showToast({
					// 	title: '请前往系统设置中开启通知权限',
					// 	icon: 'none',
					// 	duration: 3000,
					// 	success() {
					// 		// 弹出提示后，用户点击确定
					// 		uni.openSetting()
					// 	}
					// })
				}

				// this.getQuanxian()
				setTimeout(() => {
					// console.info(`222222:`)
					// uni.createPushMessage({
					// 	content: '123',
					// 	success: () => {},
					// 	fail: (error) => {
					// 		console.error(error)
					// 	}
					// })
				}, 3000)
			},
			getQuanxian() {
				let platform = uni.getSystemInfoSync().platform //首先判断app是安卓还是ios
				console.log(platform)
				if (platform == 'ios') {
					//这里是ios的方法
					console.log('我是iOS')
					var UIApplication = plus.ios.import('UIApplication')
					var app = UIApplication.sharedApplication()
					var enabledTypes = 0
					if (app.currentUserNotificationSettings) {
						var settings = app.currentUserNotificationSettings()
						enabledTypes = settings.plusGetAttribute('types')
						console.log('enabledTypes1:' + enabledTypes)
						if (enabledTypes == 0) {
							//如果enabledTypes = 0 就是通知权限没有开启
							this.tongzhi = true //这里是我写的一个弹窗上面有一个跳转开启的按钮，自行添加即可
						}
					}
					plus.ios.deleteObject(settings)
				} else if (platform == 'android') {
					//下面是安卓的方法
					console.log('我是安卓', plus.android)
					var main = plus.android.runtimeMainActivity()
					var pkName = main.getPackageName()
					var uid = main.getApplicationInfo().plusGetAttribute('uid')
					var NotificationManagerCompat = plus.android.importClass('android.support.v4.app.NotificationManagerCompat')
					//android.support.v4升级为androidx
					if (NotificationManagerCompat == null) {
						NotificationManagerCompat = plus.android.importClass('androidx.core.app.NotificationManagerCompat')
					}
					var areNotificationsEnabled = NotificationManagerCompat.from(main).areNotificationsEnabled()
					// 未开通‘允许通知’权限，则弹窗提醒开通，并点击确认后，跳转到系统设置页面进行设置
					if (!areNotificationsEnabled) {
						console.info(`fal:`, false)
						this.tongzhi = true //这里也一样未开启权限，弹出弹窗
						this.openTongZhi()
					}
				}
			},
			//开启通知
			openTongZhi() {
				//弹窗按钮绑定方法
				let platform = uni.getSystemInfoSync().platform //获取安卓还是ios
				this.tongzhi = false
				if (platform == 'ios') {
					//如果机型是ios，ios由于权限问题，可能需要手动开启
					var UIApplication = plus.ios.import('UIApplication')
					var app = UIApplication.sharedApplication()
					var settings = app.currentUserNotificationSettings()
					enabledTypes = settings.plusGetAttribute('types')
					var NSURL2 = plus.ios.import('NSURL')
					var setting2 = NSURL2.URLWithString('app-settings:')
					var application2 = UIApplication.sharedApplication()
					application2.openURL(setting2)
					plus.ios.deleteObject(setting2)
					plus.ios.deleteObject(NSURL2)
					plus.ios.deleteObject(application2)
					plus.ios.deleteObject(settings)
				} else if (platform == 'android') {
					//如果机型是安卓
					var main = plus.android.runtimeMainActivity()
					var pkName = main.getPackageName()
					var uid = main.getApplicationInfo().plusGetAttribute('uid')
					var Intent = plus.android.importClass('android.content.Intent')
					var Build = plus.android.importClass('android.os.Build')
					//android 8.0引导
					if (Build.VERSION.SDK_INT >= 26) {
						//判断安卓系统版本
						var intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS')
						intent.putExtra('android.provider.extra.APP_PACKAGE', pkName)
					} else if (Build.VERSION.SDK_INT >= 21) {
						//判断安卓系统版本
						//android 5.0-7.0
						var intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS')
						intent.putExtra('app_package', pkName)
						intent.putExtra('app_uid', uid)
					} else {
						//(<21)其他--跳转到该应用管理的详情页
						intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
						var uri = Uri.fromParts('package', mainActivity.getPackageName(), null)
						intent.setData(uri)
					}
					// 跳转到该应用的系统通知设置页
					main.startActivity(intent)
				}
			}
		}
	}
</script>

<style lang="scss">
	.color_main {
		color: #000000;
		font-weight: 900;
	}
	.box {
		margin: 20upx 0;
	}
	.box view.cu-bar {
		margin-top: 20upx;
	}

	.logo_btn {
		width: 38 * 2rpx;
		height: 38 * 2rpx;
	}
	.cu-bar.tabbar .action.add-action {
		padding-top: 56rpx !important;
	}
	.action-large {
		position: relative;
		bottom: 20rpx;
		background: transparent !important;
		image {
			width: 100rpx !important;
			height: 100rpx !important;
		}
		> view:nth-child(2) {
			position: relative;
			bottom: 10rpx;
		}
	}
	.hZindex {
		z-index: 9999999 !important;
	}
</style>
